package com.huluobo.a2109amvvmdemo.room;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.huluobo.a2109amvvmdemo.R;
import com.huluobo.a2109amvvmdemo.databinding.ActivityRoomBinding;
import com.huluobo.a2109amvvmdemo.viewbinding.BaseActivity;

import java.util.List;

public class RoomActivity extends BaseActivity<ActivityRoomBinding> {
    private AccountDatabase accountDatabase;

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        accountDatabase = Room.databaseBuilder(getApplicationContext(), AccountDatabase.class, "account.db")
                .allowMainThreadQueries()//允许主线程查询
                .build();

        viewBinding.btnSave.setOnClickListener(v -> {
            AccountBean bean = accountDatabase.getAccountDao().findAccountByLoginName(getLoginAccount());

            if (bean != null) {
                //如果账号已存在,密码也相同就不做任何操作,可以登录
                //如果账号相同,密码不同,则更新密码
                if (!bean.loginPassword.equals(getLoginPassword())) {
                    bean.loginPassword = getLoginPassword();
                    accountDatabase.getAccountDao().updateAccount(bean);
                }
            } else {
                AccountBean accountBean = new AccountBean(getLoginAccount(), getLoginPassword());
                accountDatabase.getAccountDao().insertAccount(accountBean);
            }
        });

        viewBinding.btnQuery.setOnClickListener(v -> {
            List<AccountBean> list = accountDatabase.getAccountDao().loadAccount();
            viewBinding.tvResult.setText("");

            for (int i = 0; i < list.size(); i++) {
                viewBinding.tvResult.append("账号:" + list.get(i).loginAccount);
                viewBinding.tvResult.append("密码:" + list.get(i).loginPassword);
            }
        });

        viewBinding.btnDelete.setOnClickListener(v -> {
            List<AccountBean> list = accountDatabase.getAccountDao().loadAccount();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).loginAccount.equals(getLoginAccount())) {
                    accountDatabase.getAccountDao().deleteAccount(list.get(i));
                }
            }
        });
    }

    private String getLoginPassword() {
        return viewBinding.edLoginPassword.getText().toString();
    }

    private String getLoginAccount() {
        return viewBinding.edLoginAccount.getText().toString();
    }

    @Override
    protected ActivityRoomBinding getViewBinding() {
        return ActivityRoomBinding.inflate(getLayoutInflater());
    }
}